package com.tgz.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tgz.common.R;
import com.tgz.model.Phone;
import com.tgz.service.IPhoneService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class PhoneSignController {

    @Resource
    private IPhoneService iPhoneService;

    /**
     * @Description:签到添加手机号
     * @author HeShengjin 2356899074@qq.com
     * @date 2022/12/22 14:33
     */
    @ResponseBody
    @RequestMapping(value = "/addPhoneUnique",method = RequestMethod.POST)
    public Object addPhoneUnique(@RequestParam String phone) throws Exception {
        Integer addPhoneUnique = iPhoneService.addPhoneUnique(phone);
        return R.responseWithCodeStatusMessageDataEnhance(addPhoneUnique);
    }


    /**
     * @Description:删除id
     * @author HeShengjin 2356899074@qq.com
     * @date 2022/12/22 15:13
     */
    @ResponseBody
    @RequestMapping(value = "/deleteById",method = RequestMethod.POST)
    public Object deleteById(@RequestParam Long id) throws Exception {
        boolean update = iPhoneService.update(new Phone() {{
                                                  setIsDeleted(com.tgz.constant.Phone.IS_DELETED_1);
                                                  setStatus(com.tgz.constant.Phone.STATUS_0);
                                              }},
                new LambdaUpdateWrapper<Phone>().eq(Phone::getId, id));
        return R.responseWithCodeStatusMessageDataEnhance(update ? 1 : 0);
    }


    /**
     * @Description:下载数据
     * @author HeShengjin 2356899074@qq.com
     * @date 2022/12/22 15:32
     */
    @GetMapping("/downloadExcel")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("云南特盖则科技有限公司2022年会在线签到-手机号", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Phone.class).sheet("模板").doWrite(iPhoneService.findAllPhone());
    }

    //downloadJson
    @GetMapping("/downloadJson")
    public void downloadJson(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            List<Phone> allPhone = iPhoneService.findAllPhone();
            if (!ObjectUtils.isEmpty(allPhone)){
                List<Long> phones = allPhone.stream().mapToLong(phone -> {
                    return Long.parseLong(phone.getPhone());
                }).boxed().collect(Collectors.toList());

                resp.setContentType("text/html;charset=utf-8");
                writer.write("<pre spellcheck=\"false\">");
                writer.write(String.format("[%s]",StringUtils.join(phones, ",")));
                writer.write("</pre>");
                writer.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (!ObjectUtils.isEmpty(writer)){
                writer.close();
            }
        }
    }

}
